import React from 'react';
import { Link } from 'react-router';
import { Icon, Button, Row, Col, message, Modal, Input, Form, Select } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';
import Region from '../../common/region';

const config = new Config;
const Option = Select.Option;
const FormItem = Form.Item;
const token = sessionStorage.getItem('token');

class prescriptionDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            orderId: this.props.params.orderId,
            data: {}, // 订单数据
            visible: false, // 取消订单模态框
            cancelReason: '', // 取消原因
            cancelReasonError: '', // 错误提示
            province: '', // 默认的省
            provinceList: [], // 省选择
            city: '', // 默认的市
            cityList: [], // 市选择
            area: '', // 默认的区
            areaList: [], // 区选择
        }
        this.audit = this.audit.bind(this);
        this.showCancel = this.showCancel.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.handleOk = this.handleOk.bind(this);
        this.selectCancel = this.selectCancel.bind(this);
        this.selectProvince = this.selectProvince.bind(this);
        this.selectCity = this.selectCity.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    componentWillMount() {
        this.getData();
    }

    //获取订单详情内容
    getData() {
        $.ajax({
            url: `${config.JuseOrder}/orderList/detail`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderId: this.state.orderId
            },
            success: (res) => {
                console.log('订单数据', res);
                if (res.code === 200) {
                    const order = res.data;
                    const consigneeArea = order.consigneeArea.split(' ');
                    const province = consigneeArea[0] || ' ';
                    const city = consigneeArea[1] || ' ';
                    const area = consigneeArea[2] || ' ';
                    this.handleArea(province, city);
                    this.props.form.setFieldsValue({
                        consigneeName: order.consigneeName,
                        consigneePhone: order.consigneePhone,
                        consigneeMailcode: order.consigneeMailcode,
                        province,
                        city,
                        area,
                        consigneeDetail: order.consigneeDetail,
                        buyerMessage: order.buyerMessage,
                        remark: order.remark
                    });
                    this.setState({
                        province,
                        city,
                        area,
                        data: order
                    });
                }
            }
        });
    }

    // 处理省市区
    handleArea(province, city) {
        const provinceList = Region;
        let cityList = [];
        let areaList = [];
        provinceList.forEach(item => {
            if (item.name === province) {
                cityList = item.child;
            }
        });
        cityList.forEach(item => {
            if (item.name === city) {
                areaList = item.child;
            }
        });
        this.setState({
            provinceList,
            cityList,
            areaList
        });
    }

    // 核单
    audit() {
        $.ajax({
            url: `${config.JuseOrder}/prescriptionOrder/audit`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderId: this.state.orderId
            },
            success: (data) => {
                console.log('核单', data);
                if (data.code === 200) {
                    location.href = 'index.html#/prescription';
                } else if (data.code === 204) {
                    message.error('未审核订单不能核单')
                } else if (data.code === 205) {
                    message.error('审核不通过订单不能核单')
                } else if (data.code === 206) {
                    message.error('正在审核取消预约的订单不能核单')
                } else if (data.code === 204) {
                    message.error('未审核订单不能核单')
                } else if (data.code === 207) {
                    message.error('取消预约的订单不能核单')
                }
            }
        });
    }

    // 显示取消订单模态框
    showCancel() {
        this.setState({
            visible: true
        });
    }

    // 隐藏取消订单模态框
    handleCancel() {
        this.setState({
            visible: false,
            cancelReason: '',
            cancelReasonError: ''
        });
    }

    // 选择取消原因
    selectCancel(e) {
        let cancelReasonError = this.state.cancelReasonError;
        if (e.target.value) {
            cancelReasonError = '';
        }
        this.setState({
            cancelReason: e.target.value,
            cancelReasonError
        });
    }

    // 取消订单
    handleOk() {
        const cancelReason = this.state.cancelReason;
        if (!cancelReason) {
            return this.setState({
                cancelReasonError: '请填写取消订单原因'
            });
        }
        $.ajax({
            url: `${config.JuseOrder}/prescriptionOrder/cancelPrescriptionOrder`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderId: this.state.orderId,
                userId: '1',
                reason: this.state.cancelReason
            },
            success: (data) => {
                console.log('取消订单', data);
                if (data.code === 200) {
                    location.href = 'index.html#/prescription';
                } else if (data.code === 203) {
                    message.error('已核单不能取消')
                }
            }
        });
    }

    // 选择省
    selectProvince(value) {
        const province = value;
        const city = ' ';
        const area = ' ';
        this.setState({
            province,
            city,
            area
        });
        this.props.form.setFieldsValue({
            province,
            city,
            area
        });
        this.handleArea(province, city);
    }

    // 选择市
    selectCity(value) {
        const province = this.state.province;
        const city = value;
        const area = ' ';
        this.setState({
            city,
            area
        });
        this.props.form.setFieldsValue({
            city,
            area
        });
        this.handleArea(province, city);
    }

    // 表单提交
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            console.log(values);
            if (!err) {
                $.ajax({
                    url: `${config.JuseOrder}/prescriptionOrder/updateReceivingInformation`,
                    type: 'post',
                    headers: {
                        'Authorization': 'Bearer ' + token,
                    },
                    data: {
                        orderId: this.state.data.orderId,
                        consigneeName: values.consigneeName,
                        consigneePhone: values.consigneePhone,
                        consigneeMailcode: values.consigneeMailcode,
                        consigneeArea: values.province + ' ' + values.city + ' ' + values.area,
                        consigneeDetail: values.consigneeDetail,
                        buyerMessage: values.buyerMessage,
                        remark: values.remark
                    },
                    success: (data) => {
                        console.log('修改地址', data);
                        if (data.code === 200) {
                            this.getData();
                        } else if (data.code === 203) {
                            message.error('已发货订单不能修改收货人信息')
                        }
                    }
                })
            }
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 }, };
        const formItemLayout1 = { labelCol: { span: 4 }, wrapperCol: { span: 20 }, };
        return (
            <div className='contentBox clearfix'>
                <div style={{ marginBottom: 15, padding: 10 }}>
                    <Link className='onlicksty' to='/prescription'>&lt; 返回</Link>
                </div>
                <p style={{ padding: 10, borderBottom: '1px solid #e5e5e5' }}>订单详情</p>
                <Row className='detailRow  detailRow-as'>
                    <Col span={4}><span style={{ marginRight: 10 }}>订单编号：</span><span>{this.state.data.orderId}</span></Col>
                    <Col span={4}><span style={{ marginRight: 10 }}>支付状态：</span><span>{this.state.data.isAlreadyPay ? '已支付' : '待买家付款'}</span></Col>
                </Row>
                <div>
                    <ul className='detaiList detaiList-adc'>
                        <li>
                            <Col span={6}>商品图片</Col>
                            <Col span={5}>商品名称</Col>
                            <Col span={5}>商品单价</Col>
                            <Col span={4}>商品数量</Col>
                            <Col span={4}>小记</Col>
                        </li>
                        {
                            this.state.data.productList && this.state.data.productList.map((item, i) => (
                                <li key={i}>
                                    <Col span={6}>
                                        <a href={item.imageUrl + item.listImage} target='_blank'>
                                            <img src={item.imageUrl + item.listImage} style={{ width: 50, height: 50 }} />
                                        </a>
                                    </Col>
                                    <Col span={5}>{item.productName}</Col>
                                    <Col span={5}>{item.marketPrice}</Col>
                                    <Col span={4}>{item.number}</Col>
                                    <Col span={4}>{(item.marketPrice * item.number).toFixed(2)}</Col>
                                </li>
                            ))
                        }
                    </ul>
                    <ul className='detaiList detaiList-adc'>
                        <li>
                            <Col span={6}>处方图片</Col>
                            <Col span={5}>姓名</Col>
                            <Col span={5}>身份证号</Col>
                            <Col span={4}>处方状态</Col>
                            <Col span={4}>备注</Col>
                        </li>
                        {
                            this.state.data.patientDetail
                                ?
                                <li>
                                    <Col span={6}>
                                        <a href={config.Filepath + this.state.data.patientDetail.prescriptionPicture.split(',')[0]} target='_blank'>
                                            <img src={this.state.data.patientDetail.prescriptionPicture.split(',')[0]} style={{ width: 50, height: 50 }} />
                                        </a>
                                    </Col>
                                    <Col span={5}>{this.state.data.patientDetail.patientName}</Col>
                                    <Col span={5}>{this.state.data.patientDetail.patientCardNumber}</Col>
                                    <Col span={4}>
                                        {
                                            this.state.data.prescriptionStutas === 1
                                                ?
                                                '待审核'
                                                :
                                                this.state.data.prescriptionStutas === 2
                                                    ?
                                                    '审核通过'
                                                    :
                                                    '审核不通过'
                                        }
                                    </Col>
                                    <Col span={4}>{this.state.data.patientDetail.remark}</Col>
                                </li>
                                :
                                ''
                        }
                    </ul>
                    <Form onSubmit={this.handleSubmit}>
                        <ul className='detaiList guestInfo'>
                            <li>
                                <span style={{ fontSize: 14, marginRight: 20 }}>收货人信息</span>
                                <Button htmlType="submit">修改</Button>
                            </li>
                        </ul>
                        <Row>
                            <Col span={6}>
                                <FormItem label='收货人：' {...formItemLayout}>
                                    {getFieldDecorator('consigneeName', {
                                        rules: [{
                                            required: true, max: 25, message: '请填写正确的收货人姓名',
                                        }],
                                    })(
                                        <Input />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label='联系方式：' {...formItemLayout}>
                                    {getFieldDecorator('consigneePhone', {
                                        rules: [{
                                            required: true, pattern: /^(\d{11})$/, message: '请填写正确的手机号码',
                                        }],
                                    })(
                                        <Input />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label='商品邮编：' {...formItemLayout}>
                                    {getFieldDecorator('consigneeMailcode', {
                                        rules: [{
                                            required: true, pattern: /^\d{6}$/, message: '邮政编码由6位数字组成'
                                        }],
                                    })(
                                        <Input />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <div style={{ width: '100%', }}>
                            <Row>
                                <Col span={6}>
                                    <FormItem {...formItemLayout} label="收货地址" style={{ width: '100%' }}>
                                        <Row>
                                            <Col span={20}>
                                                {getFieldDecorator('province', {
                                                })(
                                                    <Select onChange={this.selectProvince}>
                                                        {
                                                            this.state.provinceList.map((item, index) => {
                                                                return (
                                                                    <Option key={index} value={item.name}>
                                                                        {item.name}
                                                                    </Option>
                                                                )
                                                            })
                                                        }
                                                    </Select>
                                                )}
                                            </Col>
                                            <Col span={1} offset={1}>省</Col>
                                        </Row>
                                    </FormItem>
                                </Col>
                                <Col span={5}>
                                    <FormItem {...formItemLayout} label="" style={{ width: '100%' }}>
                                        <Row>
                                            <Col span={20}>
                                                {getFieldDecorator('city', {
                                                })(
                                                    <Select onChange={this.selectCity}>
                                                        {
                                                            this.state.cityList.map((item, index) => {
                                                                return (
                                                                    <Option key={index} value={item.name}>
                                                                        {item.name}
                                                                    </Option>
                                                                )
                                                            })
                                                        }
                                                    </Select>
                                                )}
                                            </Col>
                                            <Col span={1} offset={1}>市</Col>
                                        </Row>
                                    </FormItem>
                                </Col>
                                <Col span={5}>
                                    <FormItem {...formItemLayout} label="" style={{ width: '100%' }}>
                                        <Row>
                                            <Col span={20}>
                                                {getFieldDecorator('area', {
                                                })(
                                                    <Select >
                                                        {
                                                            this.state.areaList.map((item, index) => {
                                                                return (
                                                                    <Option key={index} value={item.name}>
                                                                        {item.name}
                                                                    </Option>
                                                                )
                                                            })
                                                        }
                                                    </Select>
                                                )}
                                            </Col>
                                            <Col span={1} offset={1}>区</Col>
                                        </Row>
                                    </FormItem>
                                </Col>
                                <Col span={5}>
                                    <FormItem {...formItemLayout}>
                                        {getFieldDecorator('consigneeDetail', {
                                            rules: [{
                                                required: true, message: '请填写详细地址',
                                            }],
                                        })(
                                            <Input />
                                        )}
                                    </FormItem>
                                </Col>
                            </Row>
                        </div>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout1} label='买家留言：'>
                                    {getFieldDecorator('buyerMessage', {
                                    })(
                                        <Input />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout1} label='备注：'>
                                    {getFieldDecorator('remark', {
                                    })(
                                        <Input type="textarea" rows={4} />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <div className='center' style={{ float: 'left', width: '100%' }}>
                        <Button style={{ marginRight: 50 }} onClick={this.showCancel}>取消订单</Button>
                        <Button type='primary' onClick={this.audit}>已完成核单</Button>
                    </div>
                    <Modal visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        className='xiaofrdcs-ad'
                    >
                        <div className='xiaofrdcs-ad-a'> <span>取消理由：</span><Input placeholder='必填' value={this.state.cancelReason} onChange={this.selectCancel} />
                            <p>{this.state.cancelReasonError}</p>
                        </div>
                    </Modal>
                </div>
            </div>
        )
    }
}

export default Form.create()(prescriptionDetail);
